package mspdt.ubzuuch.mn;

import java.text.NumberFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class NewApartmentActivity extends Activity {

	private ListView list;
	private ListAdapter list_adapter;
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> descriptions = new ArrayList<String>();
	ArrayList<String> prices = new ArrayList<String>();
	ArrayList<String> ids = new ArrayList<String>();
	ArrayList<String> images = new ArrayList<String>();
	private NetworkConnectionClass network;
	private boolean scrollable = false;
	private int page = 1;
	private ProgressBar progress;
	
	
  	@Override
	public void onBackPressed() {
	   finish();
	   overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newapartment);
		network=new NetworkConnectionClass(this);
		progress=(ProgressBar)findViewById(R.id.newapartment_progress);
		progress.setVisibility(View.GONE);
		list = (ListView)findViewById(R.id.new_apartment_screen_list);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewApartmentActivity.this, ViewActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("id", ids.get(arg2));
				bundle.putInt("title", R.id.title_menu_3);
				
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.no_anim);
			}
		});
		list.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

		            final int lastItem = firstVisibleItem + visibleItemCount;
		            if(lastItem == totalItemCount) {
		                // Last item is fully visible.
		            	if(scrollable)
		            	{
		            		progress.setVisibility(View.VISIBLE);
		            		scrollable=false;
		            		loadPageData(page);
		            	}
		            	else
		            	{
		            		
		            	}
		            	
		            }
			}
		});
		createTitleComponents();
		findViewById(R.id.title_menu_3).setBackgroundResource(R.drawable.text_background);
		focusOnView();
		createExpData();
	}
	public void loadPageData(int page_number)
	{
		final String url = getResources().getString(R.string.json_newapartment_url)+"&page="+page;
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   
    				   if(msg.what==1)
    				   {
    					   list_adapter.notifyDataSetChanged();
    					   //list_adapter=new ListAdapter(NewApartmentActivity.this, names, descriptions, prices, images);
        				   //list.setAdapter(list_adapter);  
    				   }
    				   else
    				   {
    					   Toast.makeText(NewApartmentActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    				   }
    				   progress.setVisibility(View.GONE);
    				   
    			      }
    			   };
    			   
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(url, 5000) && network.isNetworkConnected())
    				   {
    					   JSONObject json =new JSONfuncObject().getJSONfromURL(url);
        				   try{
        					   JSONArray  id = json.getJSONArray(getResources().getString(R.string.json_item_get_id));
        					   JSONArray  title = json.getJSONArray(getResources().getString(R.string.json_item_get_title));
            			       JSONArray  body = json.getJSONArray(getResources().getString(R.string.json_item_get_body));
            			       JSONArray  price = json.getJSONArray(getResources().getString(R.string.json_item_get_price));
            			       JSONArray  image = json.getJSONArray(getResources().getString(R.string.json_item_get_image));
            			       
            			       
        			        //Json -c мэдээллийг харгалзах хэсгүүдэд утга болгож өгөх.
            			       if(title.length()==10)
          						{
          							page+=1;
          							scrollable=true;
          						}
          						else
          						{
          							scrollable=false;
          						}
        				   for(int i=0;i<title.length();i++)
        				   {
        					   ids.add(id.getString(i));
          					   names.add(title.getString(i));
          					   descriptions.add(body.getString(i));
        					   prices.add(price.getString(i));
        					   images.add(NewApartmentActivity.this.getResources().getString(R.string.url_room_image)+image.getString(i));
        					      					
        				   }
        				   
        				   
        				   }
        				   catch(JSONException e)        {
        			        	 Log.e("log_tag", "Error parsing data "+e.toString());
        			        	 
        			        }
        				   handler.sendEmptyMessage(1);
    				   }
    				   else
    					   handler.sendEmptyMessage(0);
    				   
      				 
    				   
    			   
    				  
    			      }
    			   };
    			checkUpdate.start();
	}
	public void createExpData()
	{
		//JSON уншаагүй байгаа болохоор тест маягаар гараас шууд өгөгдөл уншиж байгаа Json уншихад Thread доторхыг солино
		names.clear();
		descriptions.clear();
		prices.clear();
		ids.clear();
		final ProgressDialog dialog = ProgressDialog.show(NewApartmentActivity.this, null, 
    			getResources().getString(R.string.dialog_please_wait), true);
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   
    				   if(msg.what==1)
    				   {
    					   list_adapter=new ListAdapter(NewApartmentActivity.this, names, descriptions, prices, images);
        				   list.setAdapter(list_adapter);  
    				   }
    				   else
    				   {
    					   Toast.makeText(NewApartmentActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    				   }
    				   
    				   dialog.dismiss();
    			      }
    			   };
    			   
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(getResources().getString(R.string.json_newapartment_url), 5000) && network.isNetworkConnected())
    				   {
    					   JSONObject json =new JSONfuncObject().getJSONfromURL(getResources().getString(R.string.json_newapartment_url));
        				   try{
        					   JSONArray  id = json.getJSONArray(getResources().getString(R.string.json_item_get_id));
        					   JSONArray  title = json.getJSONArray(getResources().getString(R.string.json_item_get_title));
            			       JSONArray  body = json.getJSONArray(getResources().getString(R.string.json_item_get_body));
            			       JSONArray  price = json.getJSONArray(getResources().getString(R.string.json_item_get_price));
            			       JSONArray  image = json.getJSONArray(getResources().getString(R.string.json_item_get_image));
            			       
            			       
        			        //Json -c мэдээллийг харгалзах хэсгүүдэд утга болгож өгөх.
            			    if(title.length()==10)
       						{
       							page+=1;
       							scrollable=true;
       						}
       						else
       						{
       							scrollable=false;
       						}
        				   for(int i=0;i<title.length();i++)
        				   {
        					   ids.add(id.getString(i));
          					   names.add(title.getString(i));
          					   descriptions.add(body.getString(i));
        					   prices.add(price.getString(i));
        					   images.add(NewApartmentActivity.this.getResources().getString(R.string.url_room_image)+image.getString(i).split(",")[0]);
        					      					
        				   }
        				   
        				   
        				   }
        				   catch(JSONException e)        {
        			        	 Log.e("log_tag", "Error parsing data "+e.toString());
        			        	 
        			        }
        				   handler.sendEmptyMessage(1);
    				   }
    				   else
    					   handler.sendEmptyMessage(0);
    				   
      				 
    				   
    			   
    				  
    			      }
    			   };
    			checkUpdate.start();
    			
		
	}
	public void onResume()
	{
		super.onResume();
		focusOnView();
	}
	private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
            	findViewById(R.id.title_scroll_view).scrollTo(findViewById(R.id.title_menu_3).getLeft()-10, 0);
            }
        });
    }
	public void createTitleComponents() {
		// Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд

		// Үндсэн товчлууруудын үйлдэл
		// Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		// Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(NewApartmentActivity.this, ItemActivityFromDB.class));
						overridePendingTransition(R.anim.top_in, R.anim.no_anim);
					}
				});
		// Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(NewApartmentActivity.this, SearchActivity.class));
						overridePendingTransition(R.anim.top_in, R.anim.no_anim);
					}
				});
		// Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(NewApartmentActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		// Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});

		// Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewApartmentActivity.this, MainActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewApartmentActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent(NewApartmentActivity.this, NewApartmentActivity.class); 
//				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
//				startActivity(intent);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewApartmentActivity.this, UBActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewApartmentActivity.this, AutomobileActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
	}
}
